﻿using System;
using System.Collections.Generic;
using System.Text;
using ThomasGIS.Geometries;

namespace ThomasGIS.Helpers
{
    public static class TopoCalculator
    {
        // 射线法判断点在面内
        public static bool Contains(Polygon polygon, Point point)
        {
            bool result = false;

            for (int i = 0; i < polygon.PartNumber; i++)
            {
                int startLoc;
                int endLoc;

                int intersectNumber = 0;

                if (i == polygon.PartNumber - 1)
                {
                    startLoc = polygon.PartList[i];
                    endLoc = polygon.PointNumber;
                }
                else
                {
                    startLoc = polygon.PartList[i];
                    endLoc = polygon.PartList[i + 1];
                }

                for (int j = startLoc; j < endLoc - 1; j++)
                {
                    Point startPoint = polygon.PointList[j];
                    Point endPoint = polygon.PointList[j + 1];

                    // 平行于X轴的直线跳过
                    if (startPoint.Y == endPoint.Y) continue;

                    // 点在直线右边跳过，只算一边的
                    double ck = (endPoint.X - startPoint.X) / (endPoint.Y - startPoint.Y);
                    double tx = startPoint.X + ck * (point.Y - startPoint.Y);
                    if (point.X >= tx) continue;

                    // Y在两者范围内即可
                    if ((startPoint.Y > point.Y && endPoint.Y < point.Y) || (startPoint.Y < point.Y && endPoint.Y > point.Y))
                    {
                        intersectNumber += 1;
                    }
                }

                if (intersectNumber % 2 == 1)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}
